package com.example.t470p.facechecktickets.View;

import android.app.Activity;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.speech.tts.TextToSpeech;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.t470p.facechecktickets.Bean.ImformationSuccessBean;
import com.example.t470p.facechecktickets.Customer.LoadingDialog;
import com.example.t470p.facechecktickets.Customer.MarqueeTextView;
import com.example.t470p.facechecktickets.Customer.RotationLoadingView;
import com.example.t470p.facechecktickets.R;
import com.example.t470p.facechecktickets.Utils.CustomString;
import com.example.t470p.facechecktickets.Utils.DesUtils;
import com.example.t470p.facechecktickets.Utils.ErrorFileUtils;
import com.example.t470p.facechecktickets.Utils.LogUtil;
import com.example.t470p.facechecktickets.Utils.MyBitmapUtils;
import com.example.t470p.facechecktickets.Utils.SPUtil;
import com.example.t470p.facechecktickets.Utils.TimeUtil;
import com.example.t470p.facechecktickets.Utils.ToastUtil;
import com.example.t470p.facechecktickets.Utils.util;
import com.example.t470p.facechecktickets.httpUtils;
import com.google.gson.Gson;
import com.synjones.handsetS8.BarReaderModule;
import com.synjones.handsetS8.BarScanResult;
import com.synjones.handsetS8.IDCardReaderModule;
import com.synjones.idcard.IDCard;
import com.synjones.idcard.IDCardReaderRetInfo;
import com.synjones.m1card.M1CardReader;
import com.synjones.multireaderlib.MultiReader;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class SHCenterActivity extends Activity implements View.OnClickListener {

    private MarqueeTextView ticket;
    private TextView number;
    private TextView numberType;
    private TextView timeBegin;
    private TextView time;
    private TextView checkState;
    private TextView backState;
    private TextView name;
    private TextView id;
    private Button btQR;
    private Button btID;
    private ImageView headShow;
    private TextView tvMode;

    //左右箭头 显示
    private ImageView leftClick;
    private ImageView rightClick;

    //计入按钮点击状态
    private boolean isIDClickAble = true;
    private boolean isQRClickAble = true;


    private static final String TAG = "zyf_MainActivity";

    private ReadCardThread ReadCardThreadhandler;
    private boolean reading = false;
    private String status = "";
    private List<ImformationSuccessBean.SaleinfoTicketListBean> saleinfoTicketList;

    /************************扫码************************/
    BarReaderModule barReaderModule;             //扫描头
    public boolean bNeedCheckTicket = true;    //检票标志位
    private String m_StrBarCode;                //二维码号码
    public String m_UpdateImgPath;            //需要上传的图片路径
    private TextToSpeech mSpeech = null;
    private static float m_voice_speed = 1.0f;   //合成语音的语速
    private static float m_voice_pitch = 1.0f;   //合成语音的语调

    /************************M1卡************************/
    boolean findingCard = false;
    private byte data[] = new byte[1024];//接收buf
    private int dataLen = 0;//接收数据长度
    IDCardReaderModule idCardReaderModule;
    public M1CardReader m1Reader;
    MultiReader multiReader;
    boolean isConnect;
    final int MESSAGE_FIND_CARD = 0x51;
    String m_strIDCard; //ID 卡号


    private static final int ReadID = 0;
    private static final int ReadQR = 1;

    public String BaseUrl;
    private LoadingDialog loadingDialog;
    private static int Page;

    Handler mHanler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case ReadID:
                    CloseReader();
                    IDCard idcard = (IDCard) msg.obj;
                    if (idcard != null) {
                        clearText();
                        m_strIDCard = idcard.getIDCardNo();
                        ticket.setText(m_strIDCard);
                        // 去网络请求  身份证
                        BaseUrl = (String) SPUtil.get(SHCenterActivity.this, CustomString.ZYFBASEURL, CustomString.BASEURL);
                        try {
                            IDSendDate(DesUtils.encrypt(m_strIDCard));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    break;

                case ReadQR:
                    clearText();
                    try {
                        // 使用解密来判断是否 可以 解密  如果可以 那么就不是票号， 那么久要 当证件号传过去 ，
                        DesUtils.decrypt(m_StrBarCode);
                        ticket.setText(m_StrBarCode);
                        // 去网络请求  二维码
                        BaseUrl = (String) SPUtil.get(SHCenterActivity.this, CustomString.ZYFBASEURL, CustomString.BASEURL);
                        IDSendDate(m_StrBarCode);
//                        QRSendDate("*110001JN607/");
                    } catch (Exception e) {
                        e.printStackTrace();
                        // 如果解密不了 那么就是 票号 按照原样传过去
                        try {
                            QRSendDate(m_StrBarCode);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }

                    break;
            }

        }
    };


    private void showDate(final ImformationSuccessBean baseBean) {

        saleinfoTicketList = baseBean.getSaleinfoTicketList();
        if (saleinfoTicketList == null) {
            saleinfoTicketList = new ArrayList<>();
        }
        //做假数据
//        for (int i = 0; i < 10; i++) {
//            ImformationSuccessBean.SaleinfoTicketListBean bean = new ImformationSuccessBean.SaleinfoTicketListBean();
//
//            bean.setTicketValidStartTime("2019-11-11 21:30:00 ");
//            bean.setTicketValidEndTime("2019-12-12 21:30:00");
//
//            if (i == 3) {
//                bean.setTicketValidStartTime("2019-12-12 21:30:00 ");
//            }
//
//            if (i == 7) {
//                bean.setTicketValidEndTime("2019-11-11 21:30:00 ");
//            }
//            bean.setTicketTypeName("上海之光" + i + "号");
//            saleinfoTicketList.add(bean);
//        }
        //获取到集合 然后首先 对有效的 数据进行判断、 用迭代器 去除 无效数据
        Iterator<ImformationSuccessBean.SaleinfoTicketListBean> iterator = saleinfoTicketList.iterator();
        while (iterator.hasNext()) {
            ImformationSuccessBean.SaleinfoTicketListBean dataBean = (ImformationSuccessBean.SaleinfoTicketListBean) iterator.next();
            if (!TimeUtil.validTime(dataBean.getTicketValidStartTime(), dataBean.getTicketValidEndTime())) {
                //如果数据不符合 那么就 取消掉
                iterator.remove();
            }
        }

        // 对有效图片进行 处理
        for (int i = 0; i < saleinfoTicketList.size(); i++) {
            for (int i1 = 0; i1 < saleinfoTicketList.size(); i1++) {
                if ( saleinfoTicketList.get(i).getPhotoDataPath().equals(saleinfoTicketList.get(i1).getPhotoDataPath())) {
                    if (saleinfoTicketList.get(i).getPhotoBase64()!= null && !saleinfoTicketList.get(i).getPhotoBase64().equals("")) {
                        saleinfoTicketList.get(i1).setPhotoBase64(saleinfoTicketList.get(i).getPhotoBase64());
                    } else if (saleinfoTicketList.get(i1).getPhotoBase64()!= null && !saleinfoTicketList.get(i1).getPhotoBase64().equals("")) {
                        saleinfoTicketList.get(i).setPhotoBase64(saleinfoTicketList.get(i1).getPhotoBase64());
                    }
                }
            }
        }


        //无效数据删除后，对后面数据进行整理
        if (saleinfoTicketList.size() > 1) {
            //如果长度大于1  说明有多个数据，那么久去做 左右显示
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    leftClick.setVisibility(View.INVISIBLE);
                    rightClick.setVisibility(View.VISIBLE);
                }
            });
            upLocationFace(0);
        } else if (saleinfoTicketList.size() == 1) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    leftClick.setVisibility(View.INVISIBLE);
                    rightClick.setVisibility(View.INVISIBLE);
                }
            });
            upLocationFace(0);
        } else {
            ToastUtil.showToast("没有查询到用户有效票记录，预安检失败");
            clearText();
        }

    }

    private void upLocationFace(final int count) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ticket.setSelected(true);
                ticket.setText(saleinfoTicketList.get(count).getTicketTypeName());
                number.setText(saleinfoTicketList.get(count).getTicketSum() + "");
                numberType.setText(saleinfoTicketList.get(count).getTicketTypeNo());
                timeBegin.setText(saleinfoTicketList.get(count).getTicketValidStartTime());
                time.setText(saleinfoTicketList.get(count).getTicketValidEndTime());
                checkState.setText(saleinfoTicketList.get(count).getCheckFlag());
                backState.setText(saleinfoTicketList.get(count).getReturnFlag());
                try {
                    name.setText(DesUtils.decrypt(saleinfoTicketList.get(count).getCertificateName()));
                    id.setText(DesUtils.decrypt(saleinfoTicketList.get(count).getCertificateNo()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (saleinfoTicketList.get(count).getPhotoBase64() != null && !saleinfoTicketList.get(count).getPhotoBase64().equals("")) {
                    headShow.setImageBitmap(MyBitmapUtils.base64ToBitmap(saleinfoTicketList.get(count).getPhotoBase64()));
                    LogUtil.v("有图片");
                } else {
                    headShow.setImageResource(R.mipmap.bgicon);
                    LogUtil.v("没有图片");
                }

            }
        });
    }


    private void QRSendDate(final String de) {

        new Thread(new Runnable() {

            private String encrypt;

            @Override
            public void run() {
                try {
                    // 先封装一个 JSON 对象
                    Map<String, String> params = new HashMap<String, String>();

                    params.put("ticketNo", de);
                    params.put("certificateNo", "");
                    String url = "http://" + BaseUrl + CustomString.DOWN_MESSAGE_URL;
                    String ss = httpUtils.postMap(url, params);

                    ImformationSuccessBean baseBean = new Gson().fromJson(ss, ImformationSuccessBean.class);

                    LogUtil.v(ss);
                    if (baseBean.getCode().equals("0")) {
                        showDate(baseBean);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }).start();

    }

    private void IDSendDate(final String id) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {

                    // 先封装一个 JSON 对象
                    Map<String, String> params = new HashMap<String, String>();
                    params.put("ticketNo", "");
                    params.put("certificateNo", id);
                    String url = "http://" + BaseUrl + CustomString.DOWN_MESSAGE_URL;
                    String ss = httpUtils.postMap(url, params);

                    ImformationSuccessBean baseBean = new Gson().fromJson(ss, ImformationSuccessBean.class);


                    LogUtil.v(ss);
                    //数据拿到后 就是去赋值了
                    if (baseBean.getCode().equals("0")) {
                        showDate(baseBean);
                    } else {
                        ToastUtil.showToast(baseBean.getMessage());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
//                    //测试数据
//                    showDate(new ImformationSuccessBean());
                    ToastUtil.showToast("获取服务器数据失败");
                }

            }
        }).start();

    }


    private void clearText() {
        headShow.setImageResource(R.mipmap.bgicon);
        ticket.setText("");
        number.setText("");
        numberType.setText("");
        time.setText("");
        timeBegin.setText("");
        checkState.setText("");
        backState.setText("");
        name.setText("");
        id.setText("");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        //取消标题
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //取消状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_shcenter);

        initView();
        String ConfigPath = getSDPath() + "/config.ini";
        GetConfig(ConfigPath);

        clearText();
        loadingDialog = new LoadingDialog(this);
//         loadingDialog = new LoadingDialog(this).setMessage("正在检票...");

        //测试记录error
//        ErrorFileUtils.getInstance().saveStringToFile();
//        ErrorFileUtils.getInstance().cleanErrorText();
    }


    private void initView() {

        ticket = (MarqueeTextView) findViewById(R.id.tv_ticket);
        number = (TextView) findViewById(R.id.tv_number);
        numberType = (TextView) findViewById(R.id.tv_number_type);
        timeBegin = (TextView) findViewById(R.id.tv_time_begin);
        time = (TextView) findViewById(R.id.tv_time_end);
        checkState = (TextView) findViewById(R.id.tv_state);
        backState = (TextView) findViewById(R.id.tv_back);
        name = (TextView) findViewById(R.id.tv_name);
        id = (TextView) findViewById(R.id.tv_id);
        tvMode = (TextView) findViewById(R.id.tv_mode);
        headShow = (ImageView) findViewById(R.id.iv_title_head);
        leftClick = (ImageView) findViewById(R.id.iv_left);
        rightClick = (ImageView) findViewById(R.id.iv_right);

        btQR = (Button) findViewById(R.id.bt_bread);
        btID = (Button) findViewById(R.id.bt_id);

        //M1卡初始化
        idCardReaderModule = IDCardReaderModule.getInstance(this);
        multiReader = idCardReaderModule.getBaseMultiReader();
        isConnect = idCardReaderModule.isOpen();
        if (!isConnect) {
            idCardReaderModule.open();
        }
        isConnect = idCardReaderModule.isOpen();
        if (null == m1Reader) {
            m1Reader = new M1CardReader(multiReader);
        }


        //扫描头初始化
        m_StrBarCode = "";
        barReaderModule = BarReaderModule.getInstance(this);
        barReaderModule.open();

        btID.setOnClickListener(this);
        btQR.setOnClickListener(this);
        leftClick.setOnClickListener(this);
        rightClick.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_id:
                Page = 0;
                clearText();
                leftClick.setVisibility(View.INVISIBLE);
                rightClick.setVisibility(View.INVISIBLE);
                loadingDialog.show();
                tvMode.setText("身份证检票");
                btID.setClickable(false);
                checkID();
                break;
            case R.id.bt_bread:
                Page = 0;
                clearText();
                leftClick.setVisibility(View.INVISIBLE);
                rightClick.setVisibility(View.INVISIBLE);
                btQR.setEnabled(false);
                tvMode.setText("二维码检票");
                loadingDialog.show();
                redScan();
                break;
            case R.id.iv_left:
                //点击了左边 就显示上一个数据
                Page = Page - 1;
                if (Page == 0) {
                    leftClick.setVisibility(View.INVISIBLE);
                    rightClick.setVisibility(View.VISIBLE);
                    upLocationFace(Page);
                } else {
                    leftClick.setVisibility(View.VISIBLE);
                    rightClick.setVisibility(View.VISIBLE);
                    upLocationFace(Page);
                }
                break;
            case R.id.iv_right:
                //点击了右边，那么就显示下一个数据
                Page = Page + 1;
                if (Page == (saleinfoTicketList.size() - 1)) {
                    leftClick.setVisibility(View.VISIBLE);
                    rightClick.setVisibility(View.INVISIBLE);
                    upLocationFace(Page);
                } else {
                    leftClick.setVisibility(View.VISIBLE);
                    rightClick.setVisibility(View.VISIBLE);
                    upLocationFace(Page);
                }
                break;

        }

    }

    private void checkID() {
        reading = true;
        ReadCardThreadhandler = new ReadCardThread();
        ReadCardThreadhandler.start();
    }

    private void redScan() {
        barReaderModule.scan(new BarReaderModule.OnScanResult() {
            @Override
            public void onScanResult(BarScanResult barScanResult) {
                if (barScanResult.code != 0) {
                    btQR.setEnabled(true);
                    loadingDialog.dismiss();
                    ToastUtil.showToast("未检测到二维码");
                    return;
                } else {
                    int end_pos = barScanResult.barMsg.lastIndexOf("\r\n");
                    if (0 > end_pos) {
                        m_StrBarCode = barScanResult.barMsg;
                    } else {
                        m_StrBarCode = barScanResult.barMsg.substring(0, end_pos);
                    }
                    if (m_StrBarCode != null && !m_StrBarCode.equals("") && !m_StrBarCode.equals("0")) {

                        m_StrBarCode = m_StrBarCode.replaceAll("\r|\n", "");
                        btQR.setEnabled(true);
                        loadingDialog.dismiss();
                        //扫描二维码成功，去发送网络请求  ReadQR
                        mHanler.sendEmptyMessage(ReadQR);
//                        Log.d(TAG, "onScanResult: 扫码成功" + m_StrBarCode);
                    } else {
                        bNeedCheckTicket = true;
                        ToastUtil.showToast("二维码数据解析失败");
                        loadingDialog.dismiss();

                    }
                }
            }
        });

    }

    //读卡线程
    class ReadCardThread extends Thread {
        public void run() {
            OpenReader();
            long t = System.currentTimeMillis();
            while (reading) {//读卡器上电需要时间，通过获取samvid判断读卡器是否已工作
                String samvID = idCardReaderModule.getSamvIDString();
                if (samvID != null && samvID.length() > 0)
                    break;
                util.sleep(50);//如果超时，则重新打开读卡器
                if (System.currentTimeMillis() - t > 2000) {
                    t = System.currentTimeMillis();
                    idCardReaderModule.close();
                    idCardReaderModule.open();
                }
            }
            try {
                IDCardReaderRetInfo retInfo;
                retInfo = idCardReaderModule.getIDcardInfo();
                if (retInfo.errCode == IDCardReaderRetInfo.ERROR_OK) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            btID.setClickable(true);
                        }
                    });
                    status = "";
                    Thread.sleep(500);
                    mHanler.obtainMessage(ReadID, retInfo.card).sendToTarget();
                    loadingDialog.dismiss();
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            btID.setClickable(true);
                        }
                    });
                    status = util.bytesToHexString(new byte[]{retInfo.sw1, retInfo.sw2, retInfo.sw3});
                    Thread.sleep(200);
                    mHanler.obtainMessage(ReadID, null).sendToTarget();
                    loadingDialog.dismiss();
                    ToastUtil.showToast("身份证读取失败");
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        public void StopRead() {
            reading = false;
            interrupted();
            try {
                join(500);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

    /**
     * 打开读卡器
     *
     * @Title OpenReader
     */
    private void OpenReader() {
        if (!idCardReaderModule.isOpen())
            idCardReaderModule.open();
    }

    /**
     * 关闭读卡器
     *
     * @Title CloseReader
     */
    private void CloseReader() {
        //停止读卡线程
        if (ReadCardThreadhandler != null) {
            ReadCardThreadhandler.StopRead();
            ReadCardThreadhandler = null;
        }
        idCardReaderModule.close();
    }

    /*
     * 获取配置信息
     */
    public boolean GetConfig(String ConfigPath) {
        boolean ret = false;
        try {
            FileInputStream fis = null; // 读
            Properties pp;

            pp = new Properties();
            fis = new FileInputStream(ConfigPath);
            pp.load(fis);

            BaseUrl = pp.get("SericeUrl").toString();
            if (BaseUrl != null) {
                SPUtil.put(SHCenterActivity.this, CustomString.ZYFBASEURL, BaseUrl);
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }

    /*
     * 获取SD卡路径
     */
    public String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState()
                .equals(android.os.Environment.MEDIA_MOUNTED);//判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();//获取跟目录
        }
        return sdDir.toString();
    }


}
